package com.ittony.controller.admin;

import com.github.pagehelper.Page;
import com.ittony.dto.DishDTO;
import com.ittony.dto.DishPageQueryDTO;
import com.ittony.entity.Dish;
import com.ittony.result.PageResult;
import com.ittony.result.Result;
import com.ittony.service.DishService;
import com.ittony.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.swing.*;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Slf4j
@Api(tags = "Dish Interface")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    @ApiOperation("Add Dish")
    public Result addDish(@RequestBody DishDTO dishDTO) {
        log.info("新增菜品：{}", dishDTO);
        dishService.addDish(dishDTO);

        String key = "dish_" + dishDTO.getCategoryId();
        cleanCache(key);
        return Result.success();
    }

    @GetMapping("/page")
    @ApiOperation("Dish Page")
    public Result dishPage(DishPageQueryDTO dishPageQueryDTO) {
        log.info("Dish Page:{}", dishPageQueryDTO);
        PageResult dishPage = dishService.dishPage(dishPageQueryDTO);

        return Result.success(dishPage);
    }

    @DeleteMapping
    @ApiOperation("Delete Dish")
    public Result deleteDish(@RequestParam("ids") Long[] dishIds) {
        log.info("Delete Dish:{}", dishIds);
        dishService.deleteBatch(dishIds);

        cleanCache("dish_*");

        return Result.success();
    }

    @GetMapping("/{id}")
    @ApiOperation("Find Dish Based on Id")
    public Result findDishById(@PathVariable("id") Long id) {
        log.info("Find Dish:{}", id);

        DishVO dishVO =  dishService.findDishById(id);

        return Result.success(dishVO);
    }

    @PutMapping
    @ApiOperation("Modify Dish")
    public Result modifyDish(@RequestBody DishDTO dishDTO) {
        log.info("Modify Dish:{}", dishDTO);
        dishService.modifyDish(dishDTO);

        cleanCache("dish_*");

        return Result.success();
    }

    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<Dish>> list(Long categoryId) {
         List<Dish> list = dishService.list(categoryId);
        return Result.success(list);
    }

    @PostMapping("/status/{status}")
    @ApiOperation("菜品起售停售")
    public Result<String> startOrStop(@PathVariable("status") Integer status, Long id) {
        dishService.startOrStop(status, id);

        cleanCache("dish_*");

        return Result.success();
    }

    private void cleanCache(String pattern) {
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

}
